﻿using System.Collections.Generic;
using NHibernate;
using RHD.Data.DAO;
using Spring.Transaction.Interceptor;

namespace RHD.Data.NHibernate {
	public abstract class GenericDAOHibernate<T, K> : IGenericDAO<T, K> {

		private ISessionFactory sessionFactory;

		public ISessionFactory SessionFactory {
			get { return sessionFactory; }
			set { sessionFactory = value; }
		}

		protected ISession CurrentSession {
			get { return sessionFactory.GetCurrentSession(); }
		}

		#region IGenericDao<T,K> Members

		[Transaction]
		public void Save(T model) {
			CurrentSession.SaveOrUpdate(model);
			CurrentSession.Flush();
		}

		[Transaction]
		public void Delete(T model) {
			CurrentSession.Delete(model);
		}

		[Transaction(ReadOnly = true)]
		public IList<T> GetAll() {
			return CurrentSession.CreateCriteria(typeof(T)).List<T>();
		}

		[Transaction(ReadOnly = true)]
		public T GetById(K id) {
			return CurrentSession.Load<T>(id);
		}

		#endregion
	}
}